<%--                                                                       --%>
<%-- Copyright (c) 2006 BroadVision, Inc.  All rights reserved.            --%>
<%--                                                                       --%>
<%-- This software is copyrighted. Under the copyright laws, this software --%>
<%-- may not be copied, in whole or in part, without prior written consent --%>
<%-- of BroadVision, Inc. or its assignees. This software is provided      --%>
<%-- under the terms of a license between BroadVision and the recipient,   --%>
<%-- and its use is subject to the terms of that license.                  --%>
<%--                                                                       --%>
<%-- This software may be protected by one or more U.S. and International  --%>
<%-- patents.  Certain applications of BroadVision One-To-One software are --%>
<%-- covered by U.S. patent 5,710,887.                                     --%>
<%--                                                                       --%>
<%-- TRADEMARKS: BroadVision and BroadVision One-To-One are registered     --%>
<%-- trademarks of BroadVision, Inc., in the United States and the         --%>
<%-- European Community, and are trademarks of BroadVision, Inc., in other --%>
<%-- countries.  The BroadVision logo, is a trademark of BroadVision,      --%>
<%-- Inc., in the United States and other countries. Additionally, IONA    --%>
<%-- and Orbix are trademarks of IONA Technologies, Ltd.  RSA, MD5, and    --%>
<%-- RC2 are trademarks of RSA Data Security, Inc.                         --%>
<%--                                                                       --%>

<%@include file="/cs/common/charset.jsp" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/webflow.tld" prefix="webflow" %>
<%@ taglib uri="/WEB-INF/webform.tld" prefix="webform" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>

<%@ page import="com.broadvision.data.client.DataManager" %>
<%@ page import="com.broadvision.data.client.Content" %>
<%@ page import="com.broadvision.data.common.ContentKey" %>
<%@ page import="com.broadvision.data.common.DataConstants" %>
<%@ page import="com.broadvision.data.common.ContentUID" %>
<%@ page import="com.broadvision.data.common.RowData" %>
<%@ page import="com.broadvision.data.common.TableData" %>

<%@ page import="com.broadvision.ssp.util.TableConstants" %>
<%@ page import="com.broadvision.ssp.webflow.Webflow" %>
<%@ page import="com.broadvision.ssp.webflow.Step" %>
<%@ page import="com.broadvision.ssp.webflow.JspStep" %>
<%@ page import="com.broadvision.ssp.webflow.StepType" %>
<%@ page import="com.broadvision.ssp.webflow.WebflowHelper" %>
<%@ page import="com.broadvision.ssp.webflow.WebflowUtil" %>
<%@ page import="com.broadvision.web.servlet.SessionVisitor" %>


<%@ page import="com.broadvision.portal.services.GenericPortalContent" %>
<%@ page import="com.broadvision.portal.services.PortalContent" %>
<%@ page import="com.broadvision.portal.services.PortalVisitor" %>

<%@ page import="java.io.IOException" %>
<%@ page import="java.util.StringTokenizer" %>

<%@page import="com.broadvision.ssp.webflow.taglib.*" %>

<script LANGUAGE="JavaScript" src='<%= response.encodeURL(EncodeTag.encodeURL(request.getContextPath() + "/formJsp/validation.js", request)) %>'></script>
<script LANGUAGE="JavaScript" src='<%= response.encodeURL(EncodeTag.encodeURL(request.getContextPath() + "/formJsp/pageflow_utils.js", request)) %>'></script>

<script LANGUAGE="JavaScript">
var _has_cancel_event = true;
</script>

<%!
  /*
   * returns true if the String is null, empty or contains all spaces
   */
   boolean riIsEmptyString(String s) {
     return ((s == null) || (s.trim().length() == 0));
   }
%>

<%
    String thisPage = "relatedItems.jsp";

    // Lets determine if this is first time through, or form has been submitted.
    boolean formDataExists = false;
    String testStr = request.getParameter("pageName");
    if( !riIsEmptyString(testStr) && testStr.compareTo(thisPage) == 0) {
      formDataExists = true;
    }

    // get the request parameters and display error message for missing data
    String errString = "";
    
    int visitorId = 0;
    if( !riIsEmptyString(request.getParameter("VisitorId")) )
      visitorId = Integer.parseInt(request.getParameter("VisitorId"));
    else
      errString = "Error: VisitorId not found in request";
    
    int serviceId = 0;
    if( !riIsEmptyString(request.getParameter("ServiceId")))
      serviceId = Integer.parseInt(request.getParameter("ServiceId"));
    else
      errString = "Error: ServiceId not found in request";
  
    int contentTypeId = 0;
    if( !riIsEmptyString(request.getParameter("ContentTypeId")))
      contentTypeId = Integer.parseInt(request.getParameter("ContentTypeId"));
    else
      errString = "Error: ContentTypeId not found in request";

    // The default related item is Editorial, so if nothing is passed in
    // then Editorial is assumed.
    int relCntTypeId = 2;
    if( !riIsEmptyString(request.getParameter("RelatedItemCntTypeId"))) {
      relCntTypeId = Integer.parseInt(request.getParameter("RelatedItemCntTypeId"));
    }

    boolean scratchContent = true;
    long contentOID = 0;
    if( !riIsEmptyString(request.getParameter("ContentOID"))) {
      contentOID = Integer.parseInt(request.getParameter("ContentOID"));
      scratchContent = false;
    }
    String selections = request.getParameter("SelectedRelatedItems");
    //String selections = ":8201:8200:8199";
      
    if( !riIsEmptyString(errString) ) {
    %><%=errString%><%
      return;
    }
    
    // Instantiate PortalVisitor object
    PortalVisitor pVisitor = null;
    try {
      SessionVisitor sessionVisitor = SessionVisitor.getInstance(request.getSession());
      pVisitor = sessionVisitor.getPortalVisitor();
    }
    catch(Exception e) {
      %>Error instantiating Portal Visitor<%
      return;
    }

    // Hold a in-memory version of the Related Items.
    List relatedItemsNames = new ArrayList();
    List relatedItemsIds = new ArrayList();
    List relatedItemsVisible = new ArrayList();
    
    // Generate the list of Related Items 
    // if the form was submitted, the the following submitted data will
    // be used to get the list
    //  -- list of related item ids RELITEM_OID_*
    //  -- list of related item names RELITEM_NAME_*
    //  -- list whether the content item is visible RELITEM_VISIBLE_*
    //  -- if DELETE, then DELETE_REL holds the oid of deleted item
    //  -- if ADD, then RELATED_ITEM_OID holds oid of item to add 
    //                  RELATED_ITEM_NAME holds name of related item to add

    try {
      int relItemNum = 1;
      Content parentCnt = null;
      // if the form was submitted, the the user either added or deleted
      // a related item. Get the original list and add/delete the item
      if (formDataExists) {

        // Get the related item oid that is marked for delete (if any).
        long relItemDelete = 0;
        if( !riIsEmptyString(request.getParameter("DELETE_REL"))) {
          relItemDelete = Long.parseLong(request.getParameter("DELETE_REL"));
        }
      
        // Attempt to read the Related Items we have so far.
        while( !riIsEmptyString(request.getParameter("RELITEM_OID_"+relItemNum))) {

          // Skip this Related Item if it was flagged for delete.
          if (relItemNum != relItemDelete) {
            String relOIDStr = request.getParameter("RELITEM_OID_"+relItemNum);
            String relNameStr = request.getParameter("RELITEM_NAME_"+relItemNum);
            String isVisibleStr = request.getParameter("RELITEM_VISIBLE_"+relItemNum);
            relatedItemsNames.add(relNameStr);
            relatedItemsIds.add(relOIDStr);
            relatedItemsVisible.add(isVisibleStr);
          }
    
          // Move on to a possible next Related Item.
          relItemNum++;
        } 
  
        // If new Related Item specified, then ADD to the list.  
        // Check the related item chosen for ADD. 
        // If specified by the Related Item Picker, we have the OID and name
        // Check if the name is correct, if not, then search by name
     
        String relOIDString = request.getParameter("RELATED_ITEM_OID");
        String relName = request.getParameter("RELATED_ITEM_NAME");

        if (!riIsEmptyString(relOIDString) || !riIsEmptyString(relName))  { 
          GenericPortalContent relatedItem = null;

          // Get the Content item and then get its name.
          long relOID = new Long(relOIDString).longValue();
          try {
            relatedItem = new GenericPortalContent(serviceId, relCntTypeId, relOID, pVisitor);
            relatedItemsNames.add(relName);
            relatedItemsIds.add(relOIDString);
            // If the user could see it, it is visible
            relatedItemsVisible.add("true");
          }
          catch (Exception e) {
            // Do nothing here, report it below, if not found by name.
          }  
        
          // Still no Related Item, so report an error.
          if (relatedItem == null) {
            // System.out.println("Could not identify the Related Item specified, "+relName);
            //cpErrorMessageString("Could not identify the Related Item specified, "+relName);
            //return;
          }
        }
      }
      else  {
        // Come to this page for the first time or just refershed the page
        // try to get the list of related items from the Database

        boolean filter = true;
        // if user is admin, then gnore qualifiers
        if( (request.getContextPath()).equals("/bvmc") ) {
          filter = false;
        }

        if( !scratchContent ) {
          GenericPortalContent portalContent = new GenericPortalContent(serviceId,
                                                       contentTypeId, 
                                                       contentOID, 
                                                       pVisitor);
        
        // Retrieve related items oid list 
        // Need the unfiltered list. Will filter here so that we
        // can remember the list for save
        List relItemOids = portalContent.getRelatedItems(DataConstants.BV_ALL_DB_CONTENT, 
                                                         false);
          
        // iterate through the list and get the name and id of related content
        Iterator iter = relItemOids.iterator();
        DataManager dataManager = new DataManager(visitorId);
        while ( iter.hasNext() ) {
          parentCnt = dataManager.getContent((ContentUID)iter.next());
          // relatedItemsNames.add(parentCnt.getStringValue("ED_NAME"));
          ContentKey contentKey = parentCnt.getKey();
          relatedItemsNames.add((contentKey.getKey()).toString());

          long parentCntOid = parentCnt.getOid();
          relatedItemsIds.add(String.valueOf( parentCntOid ));
            
          if( filter == false ) {
            // all items are visible
            relatedItemsVisible.add(String.valueOf(true));
          }
          else {
            // Qualify based filtering
            boolean isVisible = dataManager.isVisible(serviceId, contentTypeId, parentCntOid );
            relatedItemsVisible.add(String.valueOf(isVisible));
          }
        }
      }
      else {
        // handle scratch content here
        // This code is taken from AA for updateRelatedItems.xml
        DataManager dataManager = new DataManager(visitorId);
        if( !riIsEmptyString(selections)) {
          StringTokenizer tokens = new StringTokenizer(selections, ":");
          while (tokens.hasMoreTokens()) {
            String cntIdObj = tokens.nextToken();
            long cntId = Long.parseLong(cntIdObj);
            
            ContentUID cntUid = new ContentUID(contentTypeId, serviceId, cntId);
            Content cntItem = dataManager.getContent(cntUid);
            // relatedItemsNames.add(cntItem.getStringValue("ED_NAME"));
            ContentKey contentKey = parentCnt.getKey();
            relatedItemsNames.add((contentKey.getKey()).toString());
            long tmpCntOid = cntItem.getOid();
            relatedItemsIds.add(String.valueOf( tmpCntOid ) );
            if( filter == false ) {
              // all items are visible
              relatedItemsVisible.add(String.valueOf(true));
            }
            else {
              // Qualify based filtering
              boolean isVisible = dataManager.isVisible(serviceId, contentTypeId, tmpCntOid);
              relatedItemsVisible.add(String.valueOf(isVisible));
            }
          }
        }
      }
    }
    }
    catch( Exception e) {
      %>Error retrieving Related Items<%
      return;
    }
    String tmpCurrPage = request.getContextPath() + "/ep/portalPublish/relatedItems.jsp";
    String currPage = response.encodeURL(tmpCurrPage);
  
    String styleLink = "";
    if (request.getContextPath().equals("/bvmc")) { 
      styleLink = request.getContextPath() + "/mc/css/global.css";
    }
    else {
      styleLink = request.getContextPath() + "/ep/css/globalc3.css";  
    }

%>


<script language="JavaScript">
  
  // Confirm deleting a Related Item.
  function confirmRelDelete(n)
  {
    if (confirm('<bean:message key="ep.application.DeleteRelatedItem"/>'))
    {
      document.content.DELETE_REL.value = n;
      document.content.submit();
    }
  }
  
  // Invoke the itemPicker to get an Editorial content
  // Will call the callback function setRelatedContent()
  function getRelatedItem(popupURL)
  {
    // Open the window for the itemPicker dialog.
    var path = popupURL + "&VisitorId=" + "<%=visitorId%>" + "&ServiceId=" + "<%=serviceId%>" + "&relatedCnt=" + "<%=relCntTypeId%>";
    window.open(path, "itemPicker", "width=500,height=600,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
  }

  
  // Call-back function to add the Related Item.
  function setRelatedContent(oid, title)
  {
    document.content.RELATED_ITEM_NAME.value = title;
    document.content.RELATED_ITEM_OID.value = oid;
  }

  // Add the Related Item, and more, so submit the form.
  function addMoreRelatedItems()
  {
    if (document.content.RELATED_ITEM_NAME.value == null ||
        document.content.RELATED_ITEM_NAME.value == "")
    {
      alert("<bean:message  key="no.related.item.spe"/>");
      return;
    }
    document.content.submit();
  }

  // Create the output list and forward to next page  
  // output is a list of related item oids seperated by ":"
  // the output must be stored in value:RelatedItemsSelections
  function setFormAction(theForm, eventName, url) {

    theForm.action = url ;
    if ( eventName == 'Cancel' ) {
      return;
    }

    var namePattern = /^RELITEM_OID_\d+$/;
    var result = "";
    for (var i = 0; i < theForm.length; i++) {
      if (theForm.elements[i].name.match(namePattern)) {
        var temp = theForm.elements[i].value;
        result = result + ":" + temp;
      }
    }
    theForm.RelatedItemsSelections.value = result;
  }

</script>


<webflow:advance event='next' id='submit-url' />
<webflow:advance event='cancel' id='cancel-url' />

<webflow:encode url="/ep/portalPublish/itemPicker.jsp" id="popupURL" />
<% String popup = (String)pageContext.getAttribute("popupURL"); %>

<webflow:encode url="<%=currPage%>" id="currPageURL" />
<%
   // Figure out the URL to call to come back to this page in a page flow aware manner
   try {
     String currPageLink = null;   
     Webflow wf = WebflowHelper.getWebflowObject(request); // get the flow
     Step step = wf.getCurrentStep(); // get current step
     String containerURL = wf.getContainerURL();
     String param = wf.getContainerURLReqParam();
     if (null != step && step.getType() == StepType.JSP) { // sanity check
       JspStep jspStep = (JspStep) step;
       currPageLink = jspStep.getPage(); // this should point to this page
       // Test if we have a container and we are inside it
       if (jspStep.getEmbeddable() && !riIsEmptyString(containerURL)) {
         // use the container URL instead of the URL to this page
         if (containerURL.indexOf("?") >= 0) // test if request parameters exist
           currPageLink = containerURL + "&" + param + "=" + currPageLink;
         else
           currPageLink = containerURL + "?" + param + "=" + currPageLink;
       }
       if (!currPageLink.startsWith("/"))
         currPageLink = "/" + currPageLink;
       currPageLink = request.getContextPath() + currPageLink;
       // add IM CGI name if needed       
       if (WebflowUtil.isRunningUnderIM(request)) {
         String scriptName = WebflowUtil.getCGIName(request);
         if (null != scriptName)
           currPageLink = scriptName + currPageLink;
       }   
       currPageLink = response.encodeURL(currPageLink);
%>
      <webflow:encode url="<%= currPageLink %>" id="currPageURL" />
<%       
     }
   }
   catch (Exception ee) {
   }
%>

<form method="post" name="content" enctype='' 
      action='<%= (String)pageContext.getAttribute("currPageURL") %>' > 

  <webform:hidden url='<%= (String) pageContext.getAttribute("currPageURL")%>'/>
    
  <input type="hidden" name= "ContentTypeId" value= "<%=contentTypeId%>">
  <input type="hidden" name= "VisitorId" value= "<%=visitorId%>">
  <input type="hidden" name= "ServiceId" value= "<%=serviceId%>">
  <input type="hidden" name= "ContentOID" value= "<%=contentOID%>">
  <input type="hidden" name= "RelatedItemCntTypeId" value="<%=relCntTypeId%>"/>

  <input type ="hidden" name ="RelatedItemsSelections" value="" >
  <input type ="hidden" name="pageName" value="<%= thisPage %>">
  
  <table class="zoneFive" width="100%" cellspacing="0" cellpadding="0" border="0" summary="Main body">
    <tr>
      <td valign="top">
        <div class="pageTitle"><bean:message key="ep.application.AddRelatedContent"/></div>
      <div class="blockTitle">
      <span class="left">&nbsp;</span>
      <span class="right">&nbsp;</span>
    </div>
    
    <div class="blockWrap">          
       <div class="generalWrapLeft" nowrap>
          <span class="label"><bean:message key="ep.application.ContentItem"/>:</span>           
          <input type="Text" name="RELATED_ITEM_NAME" size="30" onfocus="this.blur()">
          <input type="button" name="Browse" class="inputButton" 
             value='<bean:message key="ep.application.Browse"/>' onClick="javascript:getRelatedItem('<html:rewrite page='<%=popup%>'/>')"/>
          <input type="button" name="Add" class="inputButton" 
             value='<bean:message key="ep.application.Add"/>' onClick="javascript:addMoreRelatedItems()"/>
          <input type=hidden name=RELATED_ITEM_OID value="">           
       </div>
    
     <table class="dataTable" border="0" cellspacing="1" cellpadding="2" 
        summary="Search result table" width="100%">
     <tr class="listHeader">
       <th id="Name" width="90%" align="left"><bean:message key="ep.application.RelatedContent"/>
         <input type=hidden name=DELETE_REL value=0>
         </th>
           <th id="Actions" width="10%" align="left"><bean:message key="ep.application.Actions"/></th>
       </tr>
    

    <%
      // Output each of the Related Items in our list.    
      int relItemNum = 1;
      int visibleRelItemNum = 1;
      Iterator iterNames = relatedItemsNames.iterator();
      Iterator iterIds = relatedItemsIds.iterator();
      Iterator iterVisible = relatedItemsVisible.iterator();
      String listID="listOdd";
      
      while( iterIds.hasNext() ) {
        String name = (String)iterNames.next();
        String id = (String)iterIds.next();
        String isVisible = (String)iterVisible.next();
        
        String hiddenName = "RELITEM_NAME_" + relItemNum;
        String hiddenId = "RELITEM_OID_" + relItemNum;
        String hiddenVisibleFlag = "RELITEM_VISIBLE_" + relItemNum;
        
        if(visibleRelItemNum%2==0)
          listID = "listOdd";
        else
          listID = "listEven";
    %>  
        <input type="hidden" name='<%=hiddenName%>' value='<%=name%>'/>
        <input type="hidden" name='<%=hiddenId%>' value='<%=id%>'/>
        <input type="hidden" name='<%=hiddenVisibleFlag%>' value='<%=isVisible%>'/>
        
        <% if( isVisible.equals("true") ) { %>
        
        <tr class="<%=listID%>" >
          <td headers="Name" align="left">
            <%=name%>
          </td>
          <td headers="Actions" align="left">
            <a href=javascript:confirmRelDelete('<%=relItemNum%>')>
              <img class="actionIcon" src="/portal/ca/images/action/icon_delete.gif" 
                 border="0" title="Delete">
            </a>
          </td>
        </tr>
               
        <%
            visibleRelItemNum++;
          }
          // One more put out.
          relItemNum++;
        }
        %>

    
     </table>
     <div class="pageButtonWrap" align="right">
        <input type="submit" name="Cancel" class="pageButton" value='<bean:message key="ep.application.Cancel"/>'
           onClick="try {if(!_click_form_button(this, this.form)) return false;} catch(e) {};return setFormAction(this.form, 'Cancel', '<%= (String) pageContext.getAttribute("cancel-url") %>')"/>
  
        <input type="submit" name="Submit" class="pageButton" value='<bean:message key="ep.application.Finish"/>'
           onClick="try {if(!_click_form_button(this, this.form)) return false;} catch(e) {};return setFormAction(this.form, 'Submit', '<%= (String) pageContext.getAttribute("submit-url") %>')"/>
     </div>   
   </div>   
</form>
